import { createRouter, createWebHistory,createWebHashHistory } from 'vue-router'

import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/index',
      name: 'index',
      meta:{ title:'index'}, //路由元信息
      component: () => import('../views/Index.vue'),
      children:[
        {
          path: '/index/home/:id',
          name: 'home',
          meta:{ title:'首页'},
          component: () => import('../views/Index/Home.vue'),
        },
        {
          path: '/index/order',
          name: 'order',
          meta:{ title:'订单'},
          component: () => import('../views/Index/Order.vue'),
        },
        {
          path: '/index/mine',
          name: 'mine',
          meta:{ title:'我的'},
          component: () => import('../views/Index/Mine.vue'),
          // 路由独享的守卫函数
          // beforeEnter(to,from,next){
          //   next()
          // }
        },
        {
          path:'/index',
          redirect:'/index/home'
        },
        {
          path:'/index/:notfound(.*)',
          component: () => import('../views/NotFound.vue')
        }
      ]
    },
    {
      path: '/login',
      name: 'login',
      meta:{ title:'登陆'},
      component: () => import('../views/Login.vue')
    },
    //...
    {
      path: '/',
      redirect: '/index'
    },
    // 和VueRouter3相比 404路由的写法有变化,包括嵌套路由的 404路由.
    {
      // path: new RegExp('/:id*'),
      // path:'*',
      // path:'/:id*',
      path:'/:id(.*)',
      component: () => import('../views/NotFound.vue')
    }
  ]
})

//设置全局 前置路由守卫函数
router.beforeEach((to,from,next)=>{

  //动态更新网页标题
  document.title = to.meta && to.meta.title;

  //播放路由开始动画
  NProgress.start();

  //to 新路由对象( 即将跳往的路由 )
  //from 旧路由对象( 离开的路由 )

  var token = localStorage.getItem('token');

  if( to.path == '/index/order' ){
    if( token ){ //已登录, 可以跳往订单页
      next();
    }else{ //未登录, 重定向到登录页
      next('/login');
    }
  }else{
    next();
  }
})
//设置全局 后置路由守卫函数
router.afterEach((to,from)=>{
  NProgress.done();//停止播放路由动画
})

export default router
